<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    
    <title>mongodb | 王鹏的技术博客</title>
    
    
        <meta property="og:site_name" content="王鹏的技术博客">
    
    
        <meta property="article:author" content="王 鹏">
    
    
        <link rel="icon" href="/mhexo/img/favicon.ico">
    
    
<link rel="stylesheet" href="/mhexo/css/minireset.min.css">

    
<link rel="stylesheet" href="/mhexo/css/all.min.css">

    
<link rel="stylesheet" href="/mhexo/css/csshake.min.css">

    
<link rel="stylesheet" href="/mhexo/css/hljs/lioshi.css">

    
<link rel="stylesheet" href="/mhexo/css/jquery.fancybox.min.css">

    
<link rel="stylesheet" href="/mhexo/styl/main.css">

    
<script src="/mhexo/js/jquery.min.js"></script>

    
<script src="/mhexo/js/highlight.min.js"></script>

    
<script src="/mhexo/js/jquery.fancybox.min.js"></script>

    
<script src="/mhexo/js/clipboard.min.js"></script>

<meta name="generator" content="Hexo 5.2.0"></head>
<body>
    <header>
  <div class="outer">
    <div class="inner">
      <h1 class="logo-wrap">
        <a>王鹏的技术博客<b><sup>1.1</sup></b></a>
      </h1>
    </div>
    <div class="inner">
      <nav class="main-nav">
        
          <a href="/mhexo/">首页</a>
        
          <a href="/mhexo/archives">归档</a>
        
          <a href="/mhexo/categories">分类</a>
        
          <a href="/mhexo/tags">标签</a>
        
          <a href="/mhexo/friends">友链</a>
        
          <a href="/mhexo/about">关于</a>
        
          <a target="_blank" rel="noopener" href="https://www.baidu.com">百度</a>
        
      </nav>
    </div>
  </div>
</header>
    <div class="content">
        <section class="outer">
    <article>
        <div class="article-title">
    <h2>
        <a href="/mhexo/2020/12/22/mongo/" class="shake shake-little" title="mongodb">
            
            mongodb
        </a>
    </h2>
    <div class="meta_box">
    
        
        
            
                
        
        <div class="meta meta_auth">
            <img src="/mhexo/img/default.png" alt="head" />
            <p>anonymous</p>
        </div>
    
        
        
        <div class="meta meta_date">
            <i class="fas fa-calendar-alt fa-fw" aria-hidden="true"></i>
            <p>发布于：2020年12月22日</p>
        </div>
    
        <div class="meta meta_update">
            <i class="fas fa-edit fa-fw" aria-hidden="true"></i>
            <p>更新于：2020年12月22日</p>
        </div>
    </div>
    

</div>

        <hr>
        <div class="article-entry">
            
            
            
            <h2 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a><strong>介绍</strong></h2><p>MongoDB是一种面向文档型的非关系型数据库（NoSQL），由C++编写。非关系数据库中是以键值对存储，结构不固定，易存储，减少时间和空间的开销。文档型数据库通常是以JSON或XML格式存储数据，而Mongodb使用的数据结构是<a href="https://link.zhihu.com/?target=http://bsonspec.org/%23/specification">BSON</a>（二进制JSON），和JSON相比，BSON提高了存储和扫描效率，但空间占用会更多一些。</p>
<p>在python中操作MongoDB，我们使用PyMongo，下面着重介绍。</p>
<h2 id="PyMongo的使用"><a href="#PyMongo的使用" class="headerlink" title="PyMongo的使用"></a><strong>PyMongo的使用</strong></h2><p>前提：安装了MongoDB服务器，若没有，点击<a href="https://link.zhihu.com/?target=https://www.mongodb.com/download-center/community">这里</a>安装</p>
<p><strong>1.安装</strong></p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pip3 install pymongo</span><br></pre></td></tr></table></figure>



<p><strong>2.连接</strong></p>
<ul>
<li>第1种方式：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#无密码连接</span></span><br><span class="line"><span class="keyword">import</span> pymongo</span><br><span class="line">mongo_client = pymongo.MongoClient(<span class="string">&#x27;127.0.0.1&#x27;</span>, <span class="number">27017</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#有密码连接</span></span><br><span class="line"><span class="keyword">import</span> pymongo</span><br><span class="line">mongo_client = pymongo.MongoClient(<span class="string">&#x27;127.0.0.1&#x27;</span>, <span class="number">26666</span>)</span><br><span class="line">mongo_auth = mongo_client.admin <span class="comment">#或 mongo_client[&#x27;admin&#x27;] admin为authenticationDatabase</span></span><br><span class="line">mongo_auth.authenticate(<span class="string">&#x27;用户名&#x27;</span>, <span class="string">&#x27;密码&#x27;</span>)</span><br></pre></td></tr></table></figure>

<ul>
<li>第2种方式：</li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#无密码连接</span></span><br><span class="line"><span class="keyword">import</span> pymongo</span><br><span class="line">mongo_client = pymongo.MongoClient(<span class="string">&#x27;mongodb://127.0.0.1:27017&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">#有密码连接</span></span><br><span class="line"><span class="keyword">import</span> pymongo</span><br><span class="line"><span class="keyword">import</span> urllib.parse</span><br><span class="line">mongo_username = urllib.parse.quote_plus(<span class="string">&#x27;你的用户名&#x27;</span>)</span><br><span class="line">mongo_password = urllib.parse.quote_plus(<span class="string">&#x27;密码&#x27;</span>)</span><br><span class="line">mongo_client = pymongo.MongoClient(<span class="string">&#x27;mongodb://%s:%s@127.0.0.1:26666&#x27;</span> % (mongo_username, mongo_password))</span><br><span class="line">print(mongo_client.server_info()) <span class="comment">#判断是否连接成功</span></span><br></pre></td></tr></table></figure>

<p>判断是否连接成功：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">print(mongo_client.server_info()) <span class="comment">#判断是否连接成功</span></span><br></pre></td></tr></table></figure>



<p><strong>3.获取Database 和 Collection</strong></p>
<p>若没有Database 和Collection，则会自动创建</p>
<p>第一种方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mongo_db = mongo_client[<span class="string">&#x27;你的database&#x27;</span>]</span><br><span class="line">mongo_collection = mongo_db[<span class="string">&#x27;你的collection&#x27;</span>]</span><br></pre></td></tr></table></figure>

<p>第二种方式：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">mongo_db = mongo_client.你的database</span><br><span class="line">mongo_collection = mongo_db.你的collection</span><br></pre></td></tr></table></figure>



<h2 id="CURD操作"><a href="#CURD操作" class="headerlink" title="CURD操作"></a><strong>CURD操作</strong></h2><p><strong>4.插入单条数据 insert_one()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.insert_one">insert_one()</a> 详细说明参考</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line">info = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;Inserting a Document&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span> : [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span> : datetime.datetime.now()</span><br><span class="line">&#125;</span><br><span class="line">mongo_collection.insert_one(info)</span><br></pre></td></tr></table></figure>

<p><img src="https://pic3.zhimg.com/80/v2-60eafa5b95b03af696d1137574a13a5a_720w.jpg" alt="img"></p>
<p><strong>5.插入多条数据 insert_many()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.insert_many">insert_many()</a> 详细说明参考</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line">info_1 = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_1&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;Inserting a Document&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span> : [<span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;b&#x27;</span>, <span class="string">&#x27;c&#x27;</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span> : datetime.datetime.now()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">info_2 = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_2&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;Inserting a Document&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span> : [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span> : datetime.datetime.now()</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">insert_list = [info_1, info_2]</span><br><span class="line">mongo_collection.insert_many(insert_list)</span><br></pre></td></tr></table></figure>

<p><img src="https://pic4.zhimg.com/80/v2-1846baae4ce438ec9dc490a33bb0805b_720w.jpg" alt="img"></p>
<p><strong>6.插入字符串类型的时间</strong></p>
<p>由上图可以看到插入字符串时间时，mongodb自动转成了 ISOdate类型，若需要时间在mongdb也是字符串类型，只需这样操作即可</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">datetime.datetime.now().isoformat()</span><br></pre></td></tr></table></figure>

<p><img src="https://pic3.zhimg.com/80/v2-90617acaac169dc3e39bbffce6b9f8f6_720w.jpg" alt="img"></p>
<p><strong>7.删除一条数据 delete_one()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.delete_one">delete_one()</a> 详细说明参考</p>
<p>删除一条数据。若删除条件相同匹配到多条数据，默认删除第一条</p>
<p>删除前的数据如下：</p>
<p><img src="https://pic2.zhimg.com/80/v2-8a1c123b22ee2ffc04ad0d50b1fac551_720w.jpg" alt="img"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo_collection.delete_one(&#123;<span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;a&#x27;</span>&#125;)</span><br></pre></td></tr></table></figure>

<p>删除后的数据如下：</p>
<p><img src="https://pic2.zhimg.com/80/v2-1ba001e33306fb98b4cb838cb5c96551_720w.jpg" alt="img"></p>
<p><strong>8.删除多条数据 delete_many()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.delete_many">delete_many()</a> 详细说明参考</p>
<p>删除满足条件的所有数据</p>
<p>删除前的数据如下：</p>
<p><img src="https://pic4.zhimg.com/80/v2-ac2be02d1508ebdb44eb3172553d6daf_720w.jpg" alt="img"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo_collection.delete_many(&#123;<span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;a&#x27;</span>&#125;)</span><br></pre></td></tr></table></figure>

<p>删除后的数据如下：</p>
<p><img src="https://pic3.zhimg.com/80/v2-39e7565de9a27bc17d02324f9552a43a_720w.jpg" alt="img"></p>
<p><strong>9.更新单条数据 update_one()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.update_one">update_one()</a> 详细说明参考</p>
<p>只会更新满足条件的第一条数据</p>
<p><code>update_one</code>(<em>filter</em>,<em>update</em>,<em>upsert=False</em>,<em>bypass_document_validation=False</em>,<em>collation=None</em>,<em>array_filters=None</em>,<em>session=None</em>)</p>
<ul>
<li>第一个参数 filter：更新的条件</li>
<li>第二个参数 update ： 更新的内容，必须用$操作符</li>
<li>第三个参数 upsert ： 默认False。若为True，更新条件没找到，则插入更新的内容</li>
</ul>
<p>更新前的数据如下：</p>
<p><img src="https://pic1.zhimg.com/80/v2-21727ac86abe558d9e4b8370ffa93384_720w.jpg" alt="img"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">info = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;桃子 &#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span>: <span class="string">&#x27;peach&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span>: [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span>: datetime.datetime.now()</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">update_condition = &#123;<span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_2&#x27;</span>&#125; <span class="comment">#更新的条件，也可以为多个条件</span></span><br><span class="line"><span class="comment">#更新条件多个时，需要同时满足时才会更新</span></span><br><span class="line"><span class="comment"># update_condition = &#123;&#x27;name&#x27; : &#x27;Pear&#x27;,</span></span><br><span class="line"><span class="comment">#                     &#x27;text&#x27; : &#x27;梨子&#x27;&#125;</span></span><br><span class="line"></span><br><span class="line">mongo_collection.update_one(update_condition, &#123;<span class="string">&#x27;$set&#x27;</span> : info&#125;)</span><br></pre></td></tr></table></figure>

<p>更新后的数据：</p>
<p><img src="https://pic4.zhimg.com/80/v2-af16feb1bf797071a0cc1ac434f64fe7_720w.jpg" alt="img"></p>
<p><strong>10.更新多条数据 update_many()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.update_many">update_many()</a> 详细说明参考</p>
<p>更新满足条件的所有数据</p>
<p>更新前的数据如下：</p>
<p><img src="https://pic1.zhimg.com/80/v2-cb9ca43b4fb3f38ff107f3bb7796e9e0_720w.jpg" alt="img"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">info = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;Zarten&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span>: <span class="string">&#x27;a&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span>: [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span>: datetime.datetime.now()</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">update_condition = &#123;<span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;a&#x27;</span>&#125; <span class="comment">#更新的条件</span></span><br><span class="line"><span class="comment">#更新条件多个时，需要同时满足时才会更新</span></span><br><span class="line"><span class="comment"># update_condition = &#123;&#x27;name&#x27; : &#x27;Pear&#x27;,</span></span><br><span class="line"><span class="comment">#                     &#x27;text&#x27; : &#x27;梨子&#x27;&#125;</span></span><br><span class="line"></span><br><span class="line">mongo_collection.update_many(update_condition, &#123;<span class="string">&#x27;$set&#x27;</span> : info&#125;)</span><br></pre></td></tr></table></figure>

<p><img src="https://pic2.zhimg.com/80/v2-140c22c7cc0ff386951bf527ac64b1f5_720w.jpg" alt="img"></p>
<p><strong>11.更新时，若无满足条件，则插入数据</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.update_one">update_one()</a> 详细说明参考</p>
<p>通过设置upsert为True即可</p>
<p>更新前的数据如下：</p>
<p><img src="https://pic3.zhimg.com/80/v2-58758862f06cc3afa603261a5bcd08fe_720w.jpg" alt="img"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">info = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span>: <span class="string">&#x27;Banana&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span>: <span class="string">&#x27;香蕉&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;tags&#x27;</span>: [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span>: datetime.datetime.now()</span><br><span class="line">&#125;</span><br><span class="line">update_condition = &#123;<span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;a&#x27;</span>&#125; <span class="comment">#更新的条件</span></span><br><span class="line"><span class="comment">#更新条件多个时，需要同时满足时才会更新</span></span><br><span class="line"><span class="comment"># update_condition = &#123;&#x27;name&#x27; : &#x27;Pear&#x27;,</span></span><br><span class="line"><span class="comment">#                     &#x27;text&#x27; : &#x27;梨子&#x27;&#125;</span></span><br><span class="line"></span><br><span class="line">mongo_collection.update_many(update_condition, &#123;<span class="string">&#x27;$set&#x27;</span> : info&#125;, upsert= <span class="literal">True</span>)</span><br></pre></td></tr></table></figure>

<p>更新后的数据如下：</p>
<p><img src="https://pic2.zhimg.com/80/v2-9e56c8a7c282fb0fc0347d25c4d65459_720w.jpg" alt="img"></p>
<p><strong>12.查询一条数据 find_one()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.find_one">find_one()</a> 详细说明</p>
<p>匹配第一条满足的条件的结果，这条结果以dict字典形式返回，若没有查询到，则返回None</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Banana&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;peach&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">find_result = mongo_collection.find_one(find_condition)</span><br></pre></td></tr></table></figure>



<p>可以通过<strong>projection</strong>参数来指定需要查询的字段，包括是否显示 _id ，更多具体用法参考 <a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.find">find()</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_3&#x27;</span>,</span><br><span class="line">&#125;</span><br><span class="line">select_item = mongo_collection.find_one(find_condition, projection= &#123;<span class="string">&#x27;_id&#x27;</span>:<span class="literal">False</span>, <span class="string">&#x27;name&#x27;</span>:<span class="literal">True</span>, <span class="string">&#x27;num&#x27;</span>:<span class="literal">True</span>&#125;)</span><br><span class="line">print(select_item)</span><br></pre></td></tr></table></figure>



<p><strong>13.查询范围</strong></p>
<p>查询范围具体参考<a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/tutorial.html%23range-queries">这里</a></p>
<p>范围查询通常用$ 例如：$gte 大于等于 $lt 小于；具体的$符号在文章末尾查看</p>
<p>例如：查询一段时间内的数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;date&#x27;</span> : &#123;<span class="string">&#x27;$gte&#x27;</span>:datetime.datetime(<span class="number">2018</span>,<span class="number">12</span>,<span class="number">1</span>), <span class="string">&#x27;$lt&#x27;</span>:datetime.datetime(<span class="number">2018</span>,<span class="number">12</span>,<span class="number">3</span>)&#125;</span><br><span class="line">&#125;</span><br><span class="line">select_item = mongo_collection.find_one(find_condition)</span><br><span class="line">print(select_item)</span><br></pre></td></tr></table></figure>



<p><strong>14.查询多条数据 find()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.find">find()</a> 详细说明</p>
<p>返回满足条件的所有结果，返回类型为 <a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/cursor.html%23pymongo.cursor.Cursor">Cursor</a> ，通过迭代获取每个查询结果，每个结果类型为dict字典</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Banana&#x27;</span>,</span><br><span class="line">    <span class="string">&#x27;text&#x27;</span> : <span class="string">&#x27;香蕉&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">find_result_cursor = mongo_collection.find(find_condition)</span><br><span class="line"><span class="keyword">for</span> find_result <span class="keyword">in</span> find_result_cursor:</span><br><span class="line">    print(find_result)</span><br></pre></td></tr></table></figure>



<p><strong>15.通过 _id 来查询</strong></p>
<p>查询条件中_id 类型是ObjectId类型，也就是插入时返回的对象。</p>
<p>若 _id 提供的是str类型的，我们需要转成ObjectId类型</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> bson.objectid <span class="keyword">import</span> ObjectId</span><br><span class="line">query_id_str = <span class="string">&#x27;5c00f60b20b531196c02d657&#x27;</span></span><br><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;_id&#x27;</span> : ObjectId(query_id_str),</span><br><span class="line">&#125;</span><br><span class="line">find_result = mongo_collection.find_one(find_condition)</span><br><span class="line">print(find_result)</span><br></pre></td></tr></table></figure>



<p><strong>16.查询一条数据同时删除 find_one_and_delete()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.find_one_and_delete">find_one_and_delete(</a><em>filter</em>,<em>projection=None</em>,<em>sort=None</em>,<em>session=None</em>,**<em>kwargs</em><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.find_one_and_delete">)</a> 详细说明</p>
<ul>
<li>filter：查询条件</li>
<li>projection：选择返回和不返回的字段</li>
<li>sort：list类型，当查询匹配到多条数据时，根据某个条件排序，函数返回时返回第一条数据</li>
</ul>
<p>只能返回一条数据</p>
<p>此函数的特别之处在于，它会返回被删除的信息，以字典dict形式返回</p>
<p>删除前的数据：</p>
<p><img src="https://pic4.zhimg.com/80/v2-6902940a8aec3c3b216855a0d3283083_720w.jpg" alt="img"></p>
<p><strong>17.查询并删除，匹配单条数据</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Banana&#x27;</span>,</span><br><span class="line">&#125;</span><br><span class="line">deleted_item = mongo_collection.find_one_and_delete(find_condition)</span><br><span class="line">print(deleted_item)</span><br></pre></td></tr></table></figure>



<p><strong>18.查询并删除，匹配多条数据，有选择的返回某条数据</strong></p>
<p>通过sort参数</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_2&#x27;</span>,</span><br><span class="line">&#125;</span><br><span class="line">deleted_item = mongo_collection.find_one_and_delete(find_condition, sort= [(<span class="string">&#x27;num&#x27;</span>, pymongo.DESCENDING)])</span><br><span class="line">print(deleted_item)</span><br></pre></td></tr></table></figure>

<p>删除后的数据：</p>
<p><img src="https://pic4.zhimg.com/80/v2-528f92835af3cbd40bed7ac97d733d63_720w.jpg" alt="img"></p>
<p><strong>19.计数</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.count_documents">count_documents()</a> 详细说明</p>
<p>注意：此函数在3.7版本添加，以下的版本无法使用，本人版本为3.6.3 固无法使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">find_condition = &#123;</span><br><span class="line">    <span class="string">&#x27;name&#x27;</span> : <span class="string">&#x27;Zarten_1&#x27;</span></span><br><span class="line">&#125;</span><br><span class="line">select_count = mongo_collection.count_documents(find_condition)</span><br><span class="line">print(select_count)</span><br></pre></td></tr></table></figure>



<p><strong>20.创建索引 create_index()</strong></p>
<p><a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.create_index">create_index()</a> 详细说明</p>
<p>插入数据时，已经有一个_id索引了，我们还可以自定义创建索引</p>
<p>参数 unique设置为True时，创建一个唯一索引，索引字段插入相同值时会自动报错。默认为False，为False时可以插入相同值</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo_collection.create_index(<span class="string">&#x27;name&#x27;</span>, unique= <span class="literal">True</span>)</span><br></pre></td></tr></table></figure>



<p><strong>21.获取索引信息</strong></p>
<p>list_indexes() 和 index_information() 详细说明参考<a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.index_information">这里</a></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># list_indexs = mongo_collection.list_indexes()</span></span><br><span class="line"><span class="comment"># for index in list_indexs:</span></span><br><span class="line"><span class="comment">#     print(index)</span></span><br><span class="line"></span><br><span class="line">index_info = mongo_collection.index_information()</span><br><span class="line">print(index_info)</span><br></pre></td></tr></table></figure>

<p><img src="https://pic4.zhimg.com/80/v2-f81bbaf9eb082e4a94dd0e5af2ffc84f_720w.jpg" alt="img"></p>
<p>由上图可以看到：</p>
<p>索引的名称自动作了处理，变成了别名 name_1</p>
<p><strong>22.删除索引 drop_index() 和 drop_indexes()</strong></p>
<p>详细参考<a href="https://link.zhihu.com/?target=https://api.mongodb.com/python/current/api/pymongo/collection.html%23pymongo.collection.Collection.drop_index">这里</a></p>
<p>需要使用索引的别名，没有则抛出错误</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">del_index = mongo_collection.drop_index(<span class="string">&#x27;name_1&#x27;</span>)</span><br><span class="line">print(del_index)</span><br></pre></td></tr></table></figure>



<p><strong>23.删除集合 drop()</strong></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">mongo_collection.drop()</span><br></pre></td></tr></table></figure>



<p><strong>24.符号$参考表</strong></p>
<p><img src="https://pic1.zhimg.com/80/v2-cd8dfb71a66b375a4fdba580927c88f8_720w.jpg" alt="img"></p>
<h2 id="Pymongo常用操作"><a href="#Pymongo常用操作" class="headerlink" title="Pymongo常用操作"></a>Pymongo常用操作</h2><ul>
<li><strong>根据_id查询数据插入时间排序</strong></li>
</ul>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">col.find().sort(<span class="string">&#x27;_id&#x27;</span>,<span class="number">-1</span>) <span class="comment">#根据插入时间降序</span></span><br></pre></td></tr></table></figure>



<ul>
<li><strong>根据_id查询某个日期插入的数据</strong></li>
</ul>
<p>比如查询今天插入的所有数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> bson.objectid <span class="keyword">import</span> ObjectId</span><br><span class="line"></span><br><span class="line">today_zero = datetime.datetime.strptime(datetime.datetime.now().strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>), <span class="string">&quot;%Y-%m-%d&quot;</span>)</span><br><span class="line">dummy_id = ObjectId.from_datetime(today_zero)</span><br><span class="line">results = col.find(&#123;<span class="string">&quot;_id&quot;</span>: &#123;<span class="string">&quot;$gte&quot;</span>: dummy_id&#125;&#125;).limit(<span class="number">10</span>)</span><br><span class="line"><span class="keyword">for</span> result <span class="keyword">in</span> results:</span><br><span class="line">    print(result)</span><br></pre></td></tr></table></figure>



<p>比如查询15天前的那天日期的所有插入数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> datetime</span><br><span class="line"><span class="keyword">from</span> bson.objectid <span class="keyword">import</span> ObjectId</span><br><span class="line"></span><br><span class="line">start_day_time = datetime.datetime.today() - datetime.timedelta(<span class="number">15</span>)</span><br><span class="line">end_day_time = datetime.datetime.today() - datetime.timedelta(<span class="number">14</span>)</span><br><span class="line"></span><br><span class="line">start_day_zero = datetime.datetime.strptime(start_day_time.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>), <span class="string">&quot;%Y-%m-%d&quot;</span>)</span><br><span class="line">end_day_zero = datetime.datetime.strptime(end_day_time.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>), <span class="string">&quot;%Y-%m-%d&quot;</span>)</span><br><span class="line"></span><br><span class="line">start_dummy_id = ObjectId.from_datetime(start_day_zero)</span><br><span class="line">end_dummy_id = ObjectId.from_datetime(end_day_zero)</span><br><span class="line"></span><br><span class="line">results_count = col.find(&#123;<span class="string">&quot;_id&quot;</span>: &#123;<span class="string">&quot;$gte&quot;</span>: start_dummy_id,<span class="string">&quot;$lte&quot;</span>:end_dummy_id&#125;&#125;).count()</span><br><span class="line">print(results_count)</span><br></pre></td></tr></table></figure>



<p>比如昨天插入数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">start_day_time = datetime.datetime.today() - datetime.timedelta(<span class="number">1</span>)</span><br><span class="line">end_day_time = datetime.datetime.today() - datetime.timedelta(<span class="number">0</span>)</span><br><span class="line"></span><br><span class="line">start_day_zero = datetime.datetime.strptime(start_day_time.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>), <span class="string">&quot;%Y-%m-%d&quot;</span>)</span><br><span class="line">end_day_zero = datetime.datetime.strptime(end_day_time.strftime(<span class="string">&quot;%Y-%m-%d&quot;</span>), <span class="string">&quot;%Y-%m-%d&quot;</span>)</span><br><span class="line"></span><br><span class="line">start_dummy_id = ObjectId.from_datetime(start_day_zero)</span><br><span class="line">end_dummy_id = ObjectId.from_datetime(end_day_zero)</span><br><span class="line"></span><br><span class="line">results_count = col.find(&#123;<span class="string">&quot;_id&quot;</span>: &#123;<span class="string">&quot;$gte&quot;</span>: start_dummy_id,<span class="string">&quot;$lte&quot;</span>:end_dummy_id&#125;&#125;).count()</span><br><span class="line"></span><br><span class="line">print(results_count)</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/51171906">https://zhuanlan.zhihu.com/p/51171906</a></p>

        </div>
        <div class="article-copyright">
            
    <blockquote>
        <p>
            版权声明：本文为「子曰无衣」的原创文章，博客内容遵循 署名-非商业性使用-相同方式共享 协议。<br>本文永久链接是：https://wangpdizhi.gitee.io/mhexo/2020/12/22/mongo/
        </p>
    </blockquote>


        </div>
    </article>
    

    <section id="toc-div" >
        <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#PyMongo%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="toc-text">PyMongo的使用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CURD%E6%93%8D%E4%BD%9C"><span class="toc-text">CURD操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Pymongo%E5%B8%B8%E7%94%A8%E6%93%8D%E4%BD%9C"><span class="toc-text">Pymongo常用操作</span></a></li></ol>
    </section>
    <section id="gohome" style="display: none;"><a>顶</a></section>

    <script>
        function get_top_by_link(link){
            var hnid = "#" + $(link).attr("data");
            if ($(hnid).length > 0){
                return $(hnid).offset().top;
            }else{
                return 0;
            }
        }
        //go to hn
        function gotohn(link){
            $("html,body").animate({scrollTop: get_top_by_link(link) }, 300);
        }
        //页面滚动
        function update(){
            var scrollH = $(window).scrollTop();
            if($(".toc-link")){
                $(".toc-link").each(function(i,link){
                    var mdHeight = get_top_by_link(link);
                    if(mdHeight <= scrollH + 40){
                        //高亮导航菜单
                        $('.toc-link').removeClass('on');
                        $(link).addClass('on');
                    }
                });
            }
            //返回顶部显隐
            if(scrollH < 200){
                $("#gohome").css("display","none");
            }else{
                $("#gohome").css("display","block");
            }
        }
        $(function(){
            //修复部分锚点从属关系
            if($("#toc-div >li").length > 0){
                $("#toc-div >li").appendTo($("#toc-div >ol:first"));
            }
            //返回顶部
            $('#gohome').click(function(){
                $("html,body").animate({scrollTop: 0}, 300);
                return false;
            })
            //遍历锚点
            $(".toc-link").each(function(i,link){
                $(link).attr("data",$(link).attr('href').substring(1));
                $(link).attr("href","javascript:void(0);");
                $(link).attr("onclick","gotohn(this);");
            })
            //绑定滚动事件
            $(window).bind('scroll', update);
            //初始化toc
            var first_toc = $(".toc-link")[0];
            var first_scroll = get_top_by_link(first_toc);
            var window_scroll = $(window).scrollTop();
            if(window_scroll <= first_scroll){
                $(first_toc).addClass('on');
            }
        })
    </script>

</section>
    </div>
    <footer>
    <div class="outer">
        <div class="inner">
            Powered by <a href="http://prowiki.demopage.icu/" target="_blank">ProWiki</a>
            &copy;2020 子曰无衣<br>
            <a target="_blank" rel="noopener" href="http://beian.miit.gov.cn/">冀ICP备00000000号</a>
        </div>
    </div>
</footer>

<script src="/mhexo/js/custom.js"></script>


    <script>onload_content();</script>

</body>
</html>
